﻿using System.IO;
using System.Text;
using LitJson;

namespace Basic
{
    /// <summary>
    /// json相关的辅助类
    /// 实现将字符串反序列化为特定类型（C#）
    /// </summary>
    public static class JSON
    {
        /// <summary>
        /// 从字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T FromJson<T>(string json)
        {
            return JsonMapper.ToObject<T>(json);
        }

        /// <summary>
        /// 将字节流, 反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fs"></param>
        /// <returns></returns>
        public static T FromTextReader<T>(TextReader fs) where T : class
        {
            if (fs != null)
            {
                return JsonMapper.ToObject<T>(new JsonReader(fs));
            }
            return null;
        }

        /// <summary>
        /// 将可读写目录下的文件, 反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static T FromJsonFile<T>(string p) where T : class
        {
            if (!File.Exists(p))
            {
                return null;
            }

            using (var reader = new StreamReader(p))
            {
                return FromTextReader<T>(reader);
            }
        }

        /// <summary>
        /// 将对象序列化为字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(object obj)
        {
            return JsonMapper.ToJson(obj);
        }

        /// <summary>
        /// 将对象序列化为字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="sb"></param>
        /// <param name="prettyPrint"></param>
        /// <returns></returns>
        public static void ToJson(object obj, StringBuilder sb, bool prettyPrint)
        {
            var writer = new JsonWriter(sb);
            writer.PrettyPrint = prettyPrint;
            JsonMapper.ToJson(obj, writer);
        }

        /// <summary>
        /// 将对象序列化为字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="tw"></param>
        /// <param name="prettyPrint"></param>
        /// <returns></returns>
        public static void ToJson(object obj, TextWriter tw, bool prettyPrint)
        {
            var writer = new JsonWriter(tw);
            writer.PrettyPrint = prettyPrint;
            JsonMapper.ToJson(obj, writer);
        }
    }
}
